import {
  useCallback,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';
import { Spin, message } from 'antd';
import { postMessage, MessageType } from '@inbiz/utils';
import { getMessage } from '@inbiz/react';
import { getConfig, setConfig } from '../services';
import Content from './Content';
import styles from '../index.less';

const Modal = (props: any) => {
  const { appInfo } = props;

  // 页面数据
  const [pageData, $pageData] = useState<object[]>([]);
  // 配置数据接口请求loading
  const [loading, $loading] = useState<boolean>(false);

  // 触发动作表格表单校验
  const formTableRef = useRef<any>();

  // 向上暴露验证方法
  useImperativeHandle(props.refs, () => ({
    submit: submit,
  }));

  // 初始化获取数据回填
  useEffect(() => {
    $loading(true);
    getConfig(appInfo, props.value.pageOutId)
      .then((res: any) => {
        let arr = reduction(res);
        $pageData(arr);
        $loading(false);
      })
      .catch(() => {
        $loading(false);
      });
  }, []);

  // 确定权限配置
  const submit = useCallback(async () => {
    if (formTableRef.current && formTableRef.current.submit) {
      let status = await formTableRef.current.submit();
      status && dataSet(status);
    } else {
      dataSet();
    }
  }, [pageData, props.value.pageOutId]);

  // 数据格式处理保存
  const dataSet = useCallback(
    (data?: any) => {
      $loading(true);
      let arr = toFlat(data ? data : pageData);
      setConfig(appInfo, props.value.pageOutId, arr)
        .then(() => {
          $loading(false);
          message.success(
            getMessage('PermissionConfig.message_save_successful'),
          ); // 保存成功'
          props.close && props.close();
          // message通讯
          let messageData: MessageType = {
            module: 'menuRelation',
            event: 'save',
            data: {
              pageOutId: props.value.pageOutId,
              siteOutId: appInfo.OutId,
              dataVersionId: appInfo?.SiteInfo?.DataVersionId,
            },
          };
          postMessage(messageData);
        })
        .catch(() => {
          $loading(false);
        });
    },
    [pageData, props.value.pageOutId],
  );

  // 数据拍平
  const toFlat = (data: any[]) => {
    let arr: any[] = [];
    // 页面拍平
    data.map((item) => {
      arr.push({
        outId: item.OutId,
        objectName: item.Name,
        objectValue: item.Route,
        type: 100,
        parentOutId: null,
      });
      // 动作分组拍平
      if (item.list && Array.isArray(item.list)) {
        item.list.map((aItem: any) => {
          arr.push({
            outId: aItem.tag,
            objectName: aItem.name,
            objectValue: aItem.type,
            type: 200,
            parentOutId: item.OutId,
            pageOutId: item.OutId,
          });
          // 动作拍平
          aItem.list.map((val: any) => {
            arr.push({
              outId: val.id,
              objectName: val.name,
              objectValue: val.value,
              type: 201,
              parentOutId: aItem.tag,
              pageOutId: item.OutId,
            });
          });
        });
      }
    });
    return arr;
  };

  // 数据还原
  const reduction = (data: any) => {
    let fil = data.filter((item: any) => item.OutId === props.value.pageOutId);
    let pageArr: any = [];
    data.forEach((item: any) => {
      if (item.Type === 100) {
        // 页面
        let page: {
          type: number;
          OutId: string;
          Name: string;
          Route: string;
          list: any[];
        } = {
          type: item.Type,
          OutId: item.OutId,
          Name: item.ObjectName,
          Route: item.ObjectValue,
          list: [],
        };
        // 分组赛选
        Array.isArray(item.Children) &&
          item.Children.forEach((val: any) => {
            // 分组
            let group: {
              type: number;
              tag: string;
              name: string;
              parentOutId: string;
              list: any[];
            } = {
              type: val.ObjectValue,
              tag: val.OutId,
              name: val.ObjectName,
              parentOutId: val.ParentOutId,
              list: [],
            };
            Array.isArray(val.Children) &&
              val.Children.forEach((one: any) => {
                // 动作
                group.list.push({
                  id: one.OutId,
                  name: one.ObjectName,
                  value: one.ObjectValue,
                });
              });
            page.list.push(group);
          });
        pageArr.push(page);
      }
    });
    if (!fil.length) {
      pageArr.push({
        type: 100,
        OutId: props.value.pageOutId,
        Name: props.value.pageName,
        Route: props.value.route,
        list: [],
      });
    }
    return pageArr;
  };

  // 设置页面数据
  const setPageData = (data: object[]) => {
    $pageData(data);
  };

  return (
    <>
      <div className={styles['inbiz-component-permission-config-modal']}>
        <Spin spinning={loading}>
          <Content
            {...props}
            refs={formTableRef}
            pageData={pageData}
            setPageData={setPageData}
          />
        </Spin>
      </div>
    </>
  );
};

export default Modal;
